package com.fan.leetcode;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 743. 网络延迟时间
 *
 * @author ZhangFan
 * @since 2021/8/2 下午 10:47
 */
public class Question743 {
    public int networkDelayTime(int[][] times, int n, int k) {
        List<int[]> ints = Arrays.stream(times).collect(Collectors.toList());
        Iterator<int[]> iterator = ints.iterator();
        Map<String, Integer> map = new HashMap<>();
        while (iterator.hasNext()) {
            int[] time = iterator.next();
            if (time[0] == k) {
                map.put(k + "-" + time[1], time[2]);
                iterator.remove();
            }
        }
        while (!ints.isEmpty()) {
            Iterator<int[]> iterator1 = ints.iterator();
            while (iterator.hasNext()) {
                int[] time = iterator.next();
                if (map.containsKey(k + "-" + time[0])) {
                    Integer integer = map.get(k + "-" + time[1]);
                    int i = map.get(k + "-" + time[0]) + time[2];
                    if (integer != null && integer < i) {
                        map.put(k + "-" + time[1], i);
                    } else if (integer == null) {
                        map.put(k + "-" + time[1], i);
                    }
                    iterator.remove();
                }
            }
        }
        if (map.size() != n) {
            return -1;
        }
        return Collections.max(map.values());
    }
}
